﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;

using Warehouse.Service.Data;
using Warehouse.Silverlight.Core.Infrastructure.Events;
using Warehouse.Silverlight.Core.Infrastructure.ViewModels;
using Warehouse.Silverlight.Modules.Main.Models;

namespace Warehouse.Silverlight.Modules.Main.ViewModels
{
    [Export]
    public class ProductFormViewModel : ViewModel
    {
        private readonly IProductFormModel _productFormModel;
        private readonly IEventAggregator _eventAggregator;
        private IEnumerable<Category> _categories;
        private Product _currentProduct;

        [ImportingConstructor]
        public ProductFormViewModel(IProductFormModel productFormModel, IEventAggregator eventAggregator)
        {
            _productFormModel = productFormModel;
            _eventAggregator = eventAggregator;

            Initialize();
        }

        // Override
        protected override void Initialize()
        {
            _productFormModel.GetProductByIdComplete += new EventHandler<EntityResultsArgs<Product>>(_productFormModel_GetProductByIdComplete);
            _productFormModel.GetCategoriesComplete += new EventHandler<EntityResultsArgs<Category>>(_productFormModel_GetCategoriesComplete);
            _productFormModel.SubmitChangesComplete += new EventHandler<SubmitOperationEventArgs>(_productFormModel_SubmitChangesComplete);
            _productFormModel.PropertyChanged += new PropertyChangedEventHandler(_productFormModel_PropertyChanged);

            SetCommands();

            _productFormModel.GetCategoriesAsync();

            _eventAggregator.GetEvent<SelectedProductChangedEvent>().Subscribe(ChangeCurrentProduct);
        }

        public Product CurrentProduct
        {
            get { return _currentProduct; }
            set
            {
                if (_currentProduct != value)
                {
                    _currentProduct = value;
                    RaisePropertyChanged(() => CurrentProduct);
                }
            }
        }

        public IEnumerable<Category> Categories
        {
            get { return _categories; }
            private set
            {
                if (_categories != value)
                {
                    _categories = value;
                    RaisePropertyChanged(() => Categories);
                }
            }
        }

        public ICommand RefreshCommand { get; set; }
        public ICommand SubmitCommand { get; set; }
        public ICommand CancelCommand { get; set; }


        #region EventAggregator

        public void ChangeCurrentProduct(int newId)
        {
            _productFormModel.GetProductByIdAsync(newId);
        }

        #endregion

        #region SetCommands

        private void SetCommands()
        {
            RefreshCommand = new DelegateCommand(
                () => OnRefreshCommand());
            SubmitCommand = new DelegateCommand(
                () => OnSubmitCommand());
            CancelCommand = new DelegateCommand(
                () => OnCancelCommand());
        }

        private void OnRefreshCommand()
        {
            try
            {
                if (this.IsBusy == false)
                {
                    //ProductListModel.Search()
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void OnSubmitCommand()
        {
            try
            {
                if (this.IsBusy == false)
                {
                    //ProductListModel.Search()
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void OnCancelCommand()
        {
            try
            {
                if (this.IsBusy == false)
                {
                    //ResetSearchCondition();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion

        #region Private Helpers

        private void _productFormModel_GetProductByIdComplete(object sender, EntityResultsArgs<Product> e)
        {
            if (!e.HasError)
            {
                if (_productFormModel.HasChanges)
                {
                    _productFormModel.RejectChanges();
                }

                if (e.Results.Count() == 1)
                {
                    var enumerator = e.Results.GetEnumerator();
                    enumerator.MoveNext();
                    this.CurrentProduct = enumerator.Current;
                }
            }
            else
            {
                //AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void _productFormModel_GetCategoriesComplete(object sender, EntityResultsArgs<Category> e)
        {
            if (!e.HasError)
            {
                if (_productFormModel.HasChanges)
                {
                    _productFormModel.RejectChanges();
                }
                this.Categories = e.Results;
            }
            else
            {
                //AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void _productFormModel_SubmitChangesComplete(object sender, SubmitOperationEventArgs e)
        {
            //throw new NotImplementedException();
        }

        private void _productFormModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName.Equals("HasChange"))
            {
                //RefreshCommand.RaiseCanExecuteChanged();
                //SubmitCommand.RaiseCanExecuteChanged();
                //CancelCommand.RaiseCanExecuteChanged();
            }
        }

        #endregion
    }
}
